import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"

// 只进行到hooks 没有生命周期
export default function BookList() {
  const bookListHook = useState([
    { name: "js高级设计", sale: 20, price: 18 },
    { name: "java零基础开发", sale: 29, price: 3 },
    { name: "js设计模式", sale: 100, price: 109 }
  ])
  const [bookList, setBookList] = bookListHook
  const navigateTo = useNavigate()

  const onBuyItem = (book) => {
    const newBookList = bookList.map((item) => {
      if (item === book) item.sale += 1
      return item
    })
    setBookList(newBookList)
  }
  const onRoute = (book) => {
    navigateTo("/detail?name=" + book.name + "&sale=" + book.sale)
  }
  return (
    <ul>
      {bookList.map((book) => (
        <li key={book.name} onClick={() => onRoute(book)}>
          书名：{book.name}, 销量: {book.sale}
          <button
            onClick={(e) => {
              e.stopPropagation()
              onBuyItem(book)
            }}
          >
            买一本
          </button>
        </li>
      ))}
    </ul>
  )
}
